import csv
import numpy as np
import random
from bpnn import NN

def readCsvFile(filename):
	reader = csv.reader(open(filename, "rb"), delimiter=',', quoting=csv.QUOTE_NONE)
	
	records = []
	
	for row, record in enumerate(reader):
				records.append(record)

	return np.array(records, float)

#dataMatrix=readCsvFile("data/heavy_silence_3d_std_octave_bin.csv")
#dataMatrix=readCsvFile("data/clarinet_talking_3d_zcr_octave.csv")
dataMatrix=readCsvFile("data/clarinet_talking_3d_freq_octave.csv")

#asi je nutna uprava dat do rozsahu 0-1

pat = []
for dataVector in dataMatrix:
	pat.append([dataVector[0:3], dataVector[3:4]])

globalniMax=0
for radek in pat:
	maxRadku=max(radek[0])
	if globalniMax<maxRadku:
		globalniMax=maxRadku
		
print "maximum",globalniMax

#uprava dat pokud je potreba
if globalniMax>1:
	for radek in pat:
		for el in xrange(len(radek)-1):
			radek[el]=radek[el]/globalniMax


'''
patXOR = [
[[0,0], [0]],
[[0,1], [1]],
[[1,0], [1]],
[[1,1], [0]]
]
'''
#prehazecni hodnot
random.shuffle(pat)
#rozdeleni na trenovaci a tesetovaci

def crossVali(pat,k):
	folds=[]
	pocet=len(pat)/k

	for i in range(0,k):
		folds.append(pat[(i*pocet) : ((i+1)*pocet)-1])
	return folds

valid=[]	# vyrobim si validacni data beru 1/10

for i in xrange(len(pat)/10):
	valid.append(pat.pop())

folds=crossVali(pat,10)


# create a network with two input, two hidden, and one output nodes
n = NN(3, 7, 1)
pomA=100

for i in range(0,len(folds)):
	test=[]
	train=[]
	for j in range(0,len(folds)):
		for vector in folds[j]:
			if(i!=j):
				train.append(vector)
			elif(i==j):
				test.append(vector)


	n.train(valid,train,100,0.5,0.1)
	if pomA<n.test2(valid):
		pass
		#break
	
	pomA=n.test2(valid)
	
	print "chyba valid:",n.test2(valid)
	print n.test(valid)
	#getError(test)
	#print len(train)
	#print len(test)
n.graf()	
	
'''
# train it with some patterns
n.train(pat)
# test it
n.test(pat)

n.update()
shoda=[]

for pattern in pat:
	if (pattern[1]==round(n.update(patern[0]))):
		shoda.append(1)
	else:
		shoda.appnend(0)
		

print sum(shoda)/len(shoda)*100
'''









